package lego.jbv;

import java.io.File;

import lejos.nxt.Sound;
import lejos.util.Delay;

public class SoundController extends Thread{
	private boolean update, stopNow, playing;
	private String path;
	
	public SoundController()
	{
		update = false;
		stopNow = false;
		this.setDaemon(true);
		playing = false;
		path = "";
	}
	
	public void playSound(String path)
	{
		if(path != null && new File(path).exists())
		{			
			this.path = path;
			update = true;
			
			if(!this.isAlive())
			{
				this.start();
			}
		}
	}
	
	public void run()
	{
		while(!stopNow)
		{			
			if(update)
			{
				playing = true;
				Sound.setVolume(Sound.VOL_MAX);
				Delay.msDelay(Sound.playSample(new File(path), Sound.VOL_MAX));
				update = false;
				playing = false;
			}
			
			else
			{
				Thread.yield();
			}
		}
	}
	
	public void stop()
	{
		stopNow = true;
	}
	
	public synchronized boolean isPlaying()
	{
		return playing;
	}

}
